import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main2 {
  public static void main(String[] args) throws Exception {
    Lock resultSetLock = new ReentrantLock();
    Result a = new Result("", resultSetLock);
    Productor p = new Productor(a);
    p.start();
    TimeUnit.MILLISECONDS.sleep(100);
    resultSetLock.lock();
    try {
      System.out.println("主线程获取到了锁");
      System.out.println(a.getResultHolder());
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      resultSetLock.unlock();
    }
  }

  static class Productor extends Thread {
    private Result a;

    public void setA(Result a) {
      this.a = a;
    }

    public Productor(Result a) {
      this.a = a;
    }

    @Override
    public void run() {
      a.getLock().lock();
      try {
        System.out.println("子线程获得了锁");
        TimeUnit.MILLISECONDS.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      a.setResultHolder("我是结果");
      a.getLock().unlock();
    }
  }
}

class Result {
  private Lock lock;
  private String resultHolder;

  public Result(String result, Lock lock) {
    this.resultHolder = result;
    this.lock = lock;
  }

  public void setResultHolder(String result) {
    resultHolder = result;
  }

  public String getResultHolder() {
    return resultHolder;
  }

  public Lock getLock() {
    return this.lock;
  }
}
